﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using ShopBLL;
using ShopModel;
using System.Text.RegularExpressions;

public partial class ClientPassword : BasePage
{
    #region EVENTS

    protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
    {
        SmtpClient client = new SmtpClient(ShopModel.Settings.CompanyMailHost);
        e.Message.From = new MailAddress(ShopModel.Settings.CompanyEmail, ShopModel.Settings.CompanyEmailDisplayName);
        client.Credentials = new NetworkCredential(ShopModel.Settings.CompanyMailLogin, ShopModel.Settings.CompanyMailPassword);

        e.Message.BodyEncoding = System.Text.Encoding.UTF8;
        e.Message.SubjectEncoding = System.Text.Encoding.UTF8;
        MembershipUserCollection users = Membership.FindUsersByName(e.Message.To[0].Address);
        MembershipUser user = users[e.Message.To[0].Address];
        string message = e.Message.Body;
        string password=string.Empty;
        if(message.ToLower().Contains(Resources.Language.Password.ToLower()+":"))
        {
            password = message.Substring(message.IndexOf(Resources.Language.Password+":")+(Resources.Language.Password.Length+1)).Trim();
        }
        if(message.ToLower().Contains("password:"))
        {
            password = message.Substring(message.IndexOf("Password:")+9).Trim();
        }
        if(message.ToLower().Contains("hasło:"))
        {
            password = message.Substring(message.IndexOf("Hasło:")+6).Trim();
        }
        if (!string.IsNullOrEmpty(password) && ReportsManager.Instance.ResetPass((Guid)user.ProviderUserKey, password))
        {
            NotificationTemplate Template = ReportsManager.Instance.GetNotificationTemplate("ResetNotification", CommonTools.CurrentLanguageID);
            string ShopUrl = System.Configuration.ConfigurationManager.AppSettings["ShopUrl"];
            Template.Header = Template.Header.Replace("?ShopUrl?", ShopUrl.Replace("http", "").Replace("/", "").Replace("\\", "").Replace(":", ""));
            Template.Body = Template.Body.Replace("?UserName?", user.UserName);
            Template.Body = Template.Body.Replace("?ShopUrl?", ShopUrl.Replace("http", "").Replace("/", "").Replace("\\", "").Replace(":", ""));
            Template.Body = Template.Body.Replace("?ResetLink?", ShopUrl + "/" + Resources.Language.UrlClientPassword + ".aspx?uid=" + Guid.NewGuid() + "&code=" + user.ProviderUserKey);
            e.Message.Body = Template.Body;
                /*"Witaj\nAby zmienić hasło powiązane z kontem " + user.UserName + ", kliknij poniższe łącze\n\n" +
                ShopUrl + "/" + Resources.Language.UrlClientPassword + ".aspx?uid=" + Guid.NewGuid() + "&code=" + user.ProviderUserKey +
                "\n\nJeśli łącze nie działa, skopiuj adres URL i wklej w pasku adresu nowego okna przeglądarki.\n\nDziękujemy\n" + ShopUrl;*/
            e.Message.Subject = Template.Header;// "Resetowanie hasła w serwisie " + ShopUrl.Replace("http", "").Replace("/", "").Replace("\\", "").Replace(":","") ;
            client.Send(e.Message);
        }
        else
        {
            ShowError(Resources.Language.ErrorOccurred, true);
            pnlPassword.Visible = false;
            PasswordRecovery1.Visible = false;
        }
        e.Cancel = true;
        
    }

    protected void btnChange_Click(object sender, EventArgs e)
    {
        lblError.Visible = false;
        if (Page.IsValid && ValidatePassword())
        {
                Guid guid = Guid.Empty;
                if(GuidTryParse(Request.QueryString["code"], out guid))
                {
                MembershipUser user = Membership.GetUser(guid,false);
                string oldpass = ReportsManager.Instance.GetPassReset(guid);
                if (!string.IsNullOrEmpty(oldpass) && user!=null)
                {
                    user.ChangePassword(oldpass, txtPassword.Text);
                    ReportsManager.Instance.FinishPassReset(guid);
                    ShowError(Resources.Language.PasswordSuccesfullyChanged, false);
                }
                else
                {
                    ShowError(Resources.Language.ErrorOccurred, true);
                    pnlPassword.Visible = false;
                    PasswordRecovery1.Visible = false;
                }
                }
                else
                {
                    ShowError(Resources.Language.ErrorOccurred, true);
                    pnlPassword.Visible = false;
                    PasswordRecovery1.Visible = false;
                }
        }
        else
        {
            ShowError(Resources.Language.ErrorOccurred, true);
            pnlPassword.Visible = false;
            PasswordRecovery1.Visible = false;
        }
    }
    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        Guid guid = Guid.Empty;
        if (Request.QueryString["code"] != null)
        {
            if (GuidTryParse(Request.QueryString["code"], out guid))
            {
                pnlPassword.Visible = true;
                PasswordRecovery1.Visible = false;
            }
            else
            {
                ShowError(Resources.Language.WrongPageAdress, true);
                PasswordRecovery1.Visible = false;
            }
        }
    }

    #endregion PAGE EVENTS

    private void ShowError(string error, bool isError)
    {
        lblError.Visible = true;
        lblError.ForeColor = isError ? System.Drawing.Color.Red : System.Drawing.Color.Black;
        lblError.Text = error+"</ br>";
        if (!isError)
        {
            pnlPassword.Visible = false;
            PasswordRecovery1.Visible = false;
        }
    }

    public static bool GuidTryParse(string s, out Guid result)
    {
        if (string.IsNullOrEmpty(s))
        {
            result = Guid.Empty;
            return false;
        }

        Regex format = new Regex(
            "^[A-Fa-f0-9]{32}$|" +
            "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
            "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$");
        Match match = format.Match(s);
        if (match.Success)
        {
            result = new Guid(s);
            return true;
        }
        else
        {
            result = Guid.Empty;
            return false;
        }
    }

    public bool ValidatePassword()
    {
        if(txtConfirmPassword.Text != txtPassword.Text)
        {
            ShowError(Resources.Language.ConfirmPasswordCompareErrorMessage, true);
            return false;
        }
        else if (txtPassword.Text.Length < Membership.Provider.MinRequiredPasswordLength)
            {
                ShowError(string.Format(Resources.Language.NewClient_PasswordInvalid, Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters), true);
                return false;
            }
            else
            {
                if (string.IsNullOrEmpty(Membership.PasswordStrengthRegularExpression))
                {
                    int nonAlphanumericCount = 0;
                    foreach (char c in txtPassword.Text)
                    {
                        if (!char.IsLetterOrDigit(c))
                        {
                            nonAlphanumericCount++;
                        }
                    }

                    if (nonAlphanumericCount < Membership.Provider.MinRequiredNonAlphanumericCharacters)
                    {
                        ShowError(string.Format(Resources.Language.NewClient_PasswordInvalid, Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters), true);
                        return false;
                    }
                }
                else
                {
                    Regex passwordStrength = new Regex(Membership.PasswordStrengthRegularExpression);
                    if (!passwordStrength.IsMatch(txtPassword.Text))
                    {
                        return false;
                    }
                }
            }
        return true;

    }
}
